<template>
  <div class="songlist-detail" :style="bgStyle">
    <!-- 顶部导航栏 -->
    <div class="nav-header">
      <div class="back-button" @click="goBack">
        <img src="@/assets/icon/返回.png" alt="">
      </div>
      <div class="page-title">歌单详情</div>
      <div class="right-actions">
        <img src="@/assets/icon/tabar/sousuo.png" alt="">
        <img src="@/assets/icon/xiangqing.png" alt="">
      </div>
    </div>
    
    <div v-if="songlistInfo" class="songlist-header">
      <img :src="songlistInfo.logo" :alt="songlistInfo.dissname" class="songlist-cover">
      <div class="songlist-info">
        <h1>{{ songlistInfo.dissname }}</h1>
        <div class="creator-info">
 
        </div>
        <p class="desc-link">查看简介 ></p>
      </div>
    </div>
    
    <div class="action-buttons">
      <div class="action-btn">
        <img src="@/assets/icon/分享.png" alt="">
        <span>11</span>
      </div>
      <div class="action-btn">
        <img src="@/assets/icon/信息.png" alt="">
        <span>75</span>
      </div>
      <div class="action-btn">
        <img src="@/assets/icon/添加.png" alt="">
        <span>4761</span>
      </div>
    </div>
    
    <div class="play-all-bar">
      <div class="play-btn-container" @click="playAllSongs">
        <div class="play-btn">
          <img src="@/assets/icon/播放.png" alt="播放">
        </div>
        <div class="play-text">
          <span>播放全部</span>
          <span class="song-count">{{ songlist.length }}首</span>
        </div>
      </div>
      <div class="playlist-actions">
        <img src="@/assets/icon/列表.png" alt="列表" class="list-icon">
      </div>
    </div>
    
    <div class="song-list">
      <div 
        v-for="(song, index) in songlist" 
        :key="song.songmid" 
        class="song-item"
        @click="playSong(song)"
      >
        <div class="song-index">{{ index + 1 }}</div>
        <div class="song-info">
          <div class="song-name">{{ song.songname }}</div>
          <div class="song-artist">
            <span class="quality-tag" v-if="index % 3 === 0">SQ</span>
            {{ song.singer.map(s => s.name).join(' / ') }}
          </div>
        </div>
        <div class="song-actions">
          <img src="@/assets/icon/更多.png" alt="" class="play-icon">
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { musicApi } from '@/api/music'
import { usePlayerStore } from '@/store'

const route = useRoute()
const router = useRouter()
const playerStore = usePlayerStore()
const songlist = ref([])
const songlistInfo = ref(null)
const bgStyle = reactive({
  backgroundColor: '#a88' // 默认背景色
})

// 添加返回上一页的方法
const goBack = () => {
  router.back()
}

const fetchSonglistDetail = async (id) => {
  try {
    const response = await musicApi.getSonglistDetail(id)
    if (response.data && response.data.data) {
      songlist.value = response.data.data.songlist || []
      songlistInfo.value = response.data.data
    }
  } catch (error) {
    console.error('获取歌单详情失败:', error)
  }
}

// 修改播放歌曲的方法，传递完整的歌曲信息
const playSong = async (song) => {
  try {
    // 获取歌曲URL
    const response = await musicApi.getSongUrl(song.songmid)
    
    let songUrl = ''
    // 处理URL，确保获取到的是字符串
    if (typeof response.data === 'string') {
      songUrl = response.data
    } else if (response.data.url) {
      songUrl = response.data.url
    } else if (typeof response.data.data === 'string') {
      songUrl = response.data.data
    } else if (response.data.data && response.data.data.url) {
      songUrl = response.data.data.url
    }

    if (!songUrl) {
      throw new Error('歌曲URL为空')
    }

    // 确保URL是有效的HTTP(S)链接
    if (!songUrl.startsWith('http')) {
      songUrl = `https://${songUrl}`
    }
    
    // 构建封面URL
    const coverUrl = song.albummid 
      ? `https://y.qq.com/music/photo_new/T002R300x300M000${song.albummid}.jpg` 
      : 'https://y.qq.com/mediastyle/global/img/album_300.png'
    
    // 更新播放器状态
    playerStore.currentSong = {
      songmid: song.songmid,
      songname: song.songname,
      singer: song.singer,
      cover: coverUrl,
      url: songUrl,
      // 添加当前歌单信息，用于自动播放下一首
      fromPlaylist: {
        id: route.params.id,
        index: songlist.value.findIndex(s => s.songmid === song.songmid)
      }
    }
    
    // 设置播放状态为播放
    playerStore.isPlaying = true
    
    // 可选：跳转到播放详情页
    // router.push(`/player-detail?id=${song.songmid}`)
  } catch (error) {
    console.error('播放歌曲失败:', error)
  }
}

// 添加播放下一首歌曲的方法
const playNextSong = (currentIndex) => {
  // 如果当前索引有效且不是最后一首
  if (currentIndex >= 0 && currentIndex < songlist.value.length - 1) {
    // 播放下一首
    playSong(songlist.value[currentIndex + 1])
  } else if (currentIndex === songlist.value.length - 1) {
    // 如果是最后一首，循环到第一首
    playSong(songlist.value[0])
  }
}

// 添加播放全部功能
const playAllSongs = () => {
  if (songlist.value.length > 0) {
    playSong(songlist.value[0])
  }
}

// 监听播放器状态变化，处理自动播放下一首
const setupAutoPlayNext = () => {
  // 获取音频元素
  const audioElement = document.querySelector('audio')
  if (!audioElement) return
  
  // 监听播放结束事件
  audioElement.addEventListener('ended', () => {
    console.log('歌曲播放结束，准备播放下一首')
    
    // 检查当前歌曲是否来自当前歌单
    const currentSong = playerStore.currentSong
    if (currentSong && currentSong.fromPlaylist && currentSong.fromPlaylist.id === route.params.id) {
      // 播放下一首
      playNextSong(currentSong.fromPlaylist.index)
    }
  })
}

onMounted(() => {
  const songlistId = route.params.id
  if (songlistId) {
    fetchSonglistDetail(songlistId)
  }
  
  // 设置自动播放下一首
  setupAutoPlayNext()
})
</script>

<style lang="scss" scoped>
.songlist-detail {
  padding: 0;
  background-color: #a88;
  min-height: 100vh;
  color: #fff;
  transition: background-color 0.5s ease;
}

/* 顶部导航栏样式 */
.nav-header {
  position: sticky;
  top: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 50px;
  background-color: transparent;
  z-index: 10;
  padding: 0 15px;
  
  .back-button {
    width: 36px;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    
    img {
      width: 22px;
      height: 22px;
    }
  }
  
  .page-title {
    font-size: 17px;
    font-weight: 500;
    color: #fff;
  }
  
  .right-actions {
    display: flex;
    gap: 20px;
    
    img {
      width: 22px;
      height: 22px;
    }
  }
}

.songlist-header {
  display: flex;
  padding: 20px;
  
  .songlist-cover {
    width: 120px;
    height: 120px;
    border-radius: 18px;
    object-fit: cover;
    margin-right: 15px;
  }
  
  .songlist-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    
    h1 {
      font-size: 18px;
      margin: 0 0 10px;
      color: #fff;
      line-height: 1.4;
      font-weight: 600;
    }
    
    .creator-info {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      
      .creator-avatar {
        width: 24px;
        height: 24px;
        border-radius: 50%;
        margin-right: 8px;
      }
      
      .creator-name {
        font-size: 13px;
        color: rgba(255, 255, 255, 0.8);
        margin-right: 10px;
      }
      
      .playlist-tag {
        font-size: 12px;
        color: rgba(255, 255, 255, 0.7);
      }
    }
    
    .desc-link {
      font-size: 13px;
      color: rgba(255, 255, 255, 0.8);
      margin: 5px 0 0;
    }
  }
}

.action-buttons {
  display: flex;
  justify-content: space-around;
  padding: 0 15px 15px;
  
  .action-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    border-radius: 20px;
    padding: 8px 0;
    width: 30%;
    
    img {
      width: 28px;
      height: 28px;
      margin-bottom: 5px;
      filter: brightness(1.2);
    }
    
    span {
      font-size: 13px;
      color: rgba(255, 255, 255, 0.9);
    }
  }
}

.play-all-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  padding: 10px 15px;
  border-radius: 20px 20px 0 0;
  
  .play-btn-container {
    display: flex;
    align-items: center;
    
    .play-btn {
      width: 36px;
      height: 36px;
      background-color: #fefbfb;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 10px;
      
      img {
        width: 18px;
        height: 18px;
        filter: brightness(2);
      }
    }
    
    .play-text {
      display: flex;
      align-items: baseline;
      
      span {
        color: #333;
        font-size: 16px;
        font-weight: 500;
      }
      
      .song-count {
        color: #999;
        font-size: 14px;
        font-weight: normal;
        margin-left: 5px;
      }
    }
  }
  
  .playlist-actions {
    .list-icon {
      width: 24px;
      height: 24px;
    }
  }
}

.song-list {
  background-color: #fff;
  padding: 0 15px;
  padding-bottom: 80px; /* 为底部播放器留出空间 */
  
  .song-item {
    display: flex;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f5f5f5;
    cursor: pointer;
    
    .song-index {
      width: 30px;
      text-align: center;
      color: #999;
      font-size: 14px;
    }
    
    .song-info {
      flex: 1;
      padding: 0 10px;
      
      .song-name {
        font-size: 15px;
        margin-bottom: 5px;
        color: #333;
      }
      
      .song-artist {
        font-size: 12px;
        color: #999;
        display: flex;
        align-items: center;
        
        .quality-tag {
          display: inline-block;
          padding: 1px 3px;
          background-color: #ffbd20;
          color: #fff;
          border-radius: 2px;
          font-size: 10px;
          margin-right: 5px;
          font-weight: bold;
        }
      }
    }
    
    .song-actions {
      padding: 0 5px;
      
      .play-icon {
        width: 30px;
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #1eaef4;
      }
    }
  }
}
</style>